package cc.booku.owlbox.OnlineDatabase;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;

import androidx.appcompat.app.AppCompatActivity;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import cc.booku.owlbox.ArtDesign.SystemUtil;
import cc.booku.owlbox.FileOperations.FileoOperations;
import cc.booku.owlbox.R;
import cc.booku.owlbox.RsaUtil.Decrypt;
import cc.booku.owlbox.VideoPlayer.PlayerActivity;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;

public class LayPageActivity extends AppCompatActivity {

    private HorizontalListView hl_laylist;
    private List<LayPage_C> layPageCList = new ArrayList<LayPage_C>();
    private GridView hg_datalist;
    private String lay_class = null;
    private ImageView iv_back;
    private TextView Fromfileurl;
    private List<LayClass_C> layClass_cList = new ArrayList<LayClass_C>();
    private String ProfilePath = Environment.getExternalStorageDirectory() + File.separator + "OwlDatabase" + File.separator + "Profile.txt";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_culay_page);
        SystemUtil.setStatusBarColor(this, Color.parseColor("#448aca"));

        hg_datalist = (GridView) findViewById(R.id.hg_datalist);
        hl_laylist = (HorizontalListView) findViewById(R.id.hl_laylist);
        iv_back = (ImageView) findViewById(R.id.iv_back);
        Fromfileurl = (TextView) findViewById(R.id.fromfileurl);
        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        Intent intent = getIntent();
        // intent.getStringExtra("vod_class1");//给链接调用的
        lay_class = intent.getStringExtra("vod_class1");//给链接调用的
        String laypage_api = intent.getStringExtra("laypage_api");//给链接调用的
        try {
            init_video(laypage_api + lay_class + "&vodpage=0");//初始化第一页
        } catch (Exception e) {

            Log.i("response===========>", "网络连接失败");
//异常处理
        }
//        String ProfileStr = FileoOperations.readFromSDFile(this, ProfilePath);
//
//
//        try {
//
//            //读取配置文件信息
//            JSONObject obj = JSONObject.parseObject(ProfileStr);
//            String result = obj.getString("UN分页接口");
//
//            String ciphertext = obj.getString("地址密文");
//            String res = Decrypt.RsaDecrypt(LayPageActivity.this,ciphertext);
//            init_video(res+result+lay_class+"&vodpage=0");//初始化第一页
//        }catch (Exception e) {
//
//            Log.i("response===========>",lay_class);
////异常处理
//        }


        laylist(intent.getStringExtra("count1"));


    }


    private LayClass_C layClassC;

    private void init_video(String url) {

        layClass_cList.clear();

        OkHttpClient client = new OkHttpClient();
        Request request = new Request
                .Builder()
                .url(url)//要访问的链接
                .build();

        Call call = client.newCall(request);
        call.enqueue(new okhttp3.Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, okhttp3.Response response) throws IOException {
                String res = response.body().string();
//               // Log.i("onResponse===========>",res);
//                Message msg = new Message();
//                msg.what = 16;
//                Bundle bundle = new Bundle();
//                bundle.putString("jsondata",res);  //往Bundle中存放数据
//                // bundle.putString("text2","Time：2016-11-03");  //往Bundle中put数据
//                msg.setData(bundle);//mes利用Bundle传递数据
//                handler.sendMessage(msg);//用activity中的handler发送消息

                List<LayClass_C> collectionStationCList = JSON.parseArray(res, LayClass_C.class);
                for (LayClass_C normVideo : collectionStationCList) {
                    layClassC = new LayClass_C();

//    vod_score  ---评分
//    vod_name	----影片名称
//    vod_class  ----类型
//    vod_pic ----图片地址
//    vod_play_url --视频地址
//    vod_add_time  ---添加日期

//    vod_actor ---演员
//    vod_director ---导演
//    vod_blurb  ---影片简介
//    vod_area  ---地区
//    vod_year  ---上映年份
//    vod_lang  ---语言

                    String vod_score = normVideo.getVod_score();
                    String vod_name = normVideo.getVod_name();
                    String vod_class = normVideo.getVod_class();
                    String vod_add_time = normVideo.getVod_add_time();
                    String vod_pic = normVideo.getVod_pic();
                    String vod_play_url = normVideo.getVod_play_url();

                    String vod_actor = normVideo.getVod_actor();
                    String vod_director = normVideo.getVod_director();
                    String vod_blurb = normVideo.getVod_blurb();
                    String vod_area = normVideo.getVod_area();
                    String vod_year = normVideo.getVod_year();
                    String vod_lang = normVideo.getVod_lang();
                    String vod_id = normVideo.getVod_id();

                    // Log.d("ImageviewHolder", "显示图片url======" + vod_pic);

                    layClassC.setVod_score("评分:" + vod_score);
                    layClassC.setVod_name(vod_name);
                    layClassC.setVod_class(vod_class + "#" + vod_year + "#" + vod_area + "#" + vod_lang + "#" + vod_id);
                    layClassC.setVod_add_time(vod_add_time);
                    layClassC.setVod_pic(vod_pic);
                    layClassC.setVod_pic_url(vod_pic);
                    layClassC.setVod_play_url(vod_play_url);
                    layClassC.setVod_value_add("导演：" + vod_director + "\n演员：" + vod_actor + "\n类型：" + vod_class + "\n上映地区：" + vod_area + "\n上映年份：" + vod_year + "\n语言：" + vod_lang + "\n$片名：" + vod_name + "\n剧情简介：" + vod_blurb);


                    layClass_cList.add(layClassC);


                }
                Message msg = new Message();
                msg.what = 16;
                handler.sendMessage(msg);//用activity中的handler发送消息
            }
        });

    }


    private LayPage_C page;

    public void laylist(String count) {
        //根据每页多少数据分出多少页
        int icount = Integer.parseInt(count);
        int pagecount = icount / 60;
        //pagecount分出页数如30页
        //将页数循环遍历到subpage实体类
        //可以给message执行

        for (int pa = 1; pa <= pagecount; pa++) {
            page = new LayPage_C();
            page.setPagename("第" + pa + "页");
            page.setPagecount(pa * 60);//60为1页
            layPageCList.add(page);
            //Log.d("1111111111", "pagename" + pa+"页");

        }
        Message msg = new Message();
        msg.what = 9;
        handler.sendMessage(msg);//用activity中的handler发送消息

        //Log.d("1111111111", "pagecountpagecountpagecountpagecount=== " + pagecount);

    }


    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 9:

                    clickpageData((ArrayList<LayPage_C>) layPageCList);
                    break;

                case 11:
                    layClass_cList.clear();
                    String pgcount1 = msg.getData().getString("pgcount1");//接受msg传递过来的参数

                    Intent intent = getIntent();
                    String laypage_api = intent.getStringExtra("laypage_api");//给链接调用的
                    init_video(laypage_api + lay_class + "&vodpage=" + pgcount1);//初始化第一页

//                    String ProfileStr = FileoOperations.readFromSDFile(LayPageActivity.this, ProfilePath);
//
//                    try {
//
//                        //读取配置文件信息
//                        JSONObject obj = JSONObject.parseObject(ProfileStr);
//                        String result = obj.getString("UN分页接口");
//
//                        String ciphertext = obj.getString("地址密文");
//                        String res = Decrypt.RsaDecrypt(LayPageActivity.this,ciphertext);
//
//                        init_video(res+result+lay_class+"&vodpage="+pgcount1);//初始化第一页
//                    }catch (Exception e) {
//
//                        Log.i("response===========>",lay_class);
////异常处理
//                    }
                    break;


                case 16:
//                    String jsondata = msg.getData().getString("jsondata");//接受msg传递过来的参数
//                    searchdata.setText(jsondata);

                    listClickListener((ArrayList<LayClass_C>) layClass_cList);
                    break;

            }
        }
    };


    private LayPageAdapter layPageAdapter;

    public void clickpageData(ArrayList<LayPage_C> layPageCList) {

        layPageAdapter = new LayPageAdapter(R.layout.laypage_item, this, layPageCList);


        hl_laylist.setAdapter(layPageAdapter);
        hl_laylist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                final TextView pgname = (TextView) view.findViewById(R.id.pgname);//名称
                final TextView pgcount = (TextView) view.findViewById(R.id.pgcount);//数量

                String pgname1 = pgname.getText().toString();
                String pgcount1 = pgcount.getText().toString();

                // pgname.setTextColor(Color.parseColor("#EE5C42"));

                Fromfileurl.setText("当前页：" + pgname1);

                Message msg = new Message();
                Bundle bundle = new Bundle();
                bundle.putString("pgcount1", pgcount1);
                msg.setData(bundle);//mes利用Bundle传递数据
                msg.what = 11;
                handler.sendMessage(msg);//用activity中的handler发送消息


            }
        });


    }


    class LayPageAdapter extends BaseAdapter implements ListAdapter {


        private ArrayList<LayPage_C> layPageCList;
        private int id;
        private Context context;
        private LayoutInflater inflater;

        public LayPageAdapter(int subpage_item, LayPageActivity context, ArrayList<LayPage_C> layPageCList) {
            this.layPageCList = layPageCList;
            this.context = context;
            this.id = subpage_item;
            inflater = LayoutInflater.from(context);

        }

        @Override
        public int getCount() {
            return layPageCList.size();
        }

        @Override
        public Object getItem(int i) {
            return layPageCList.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @SuppressLint("WrongConstant")
        @Override

        public View getView(int i, View view, ViewGroup viewGroup) {

            TextView pgname = null;
            TextView pgcount = null;
            LayPageAdapter.ViewHolder viewHolder;
            if (view == null) {
                view = inflater.inflate(id, null);
                pgname = (TextView) view.findViewById(R.id.pgname);
                pgcount = (TextView) view.findViewById(R.id.pgcount);
                view.setTag(new ViewHolder(pgname, pgcount));
            } else {
                LayPageAdapter.ViewHolder viewHolder1 = (LayPageAdapter.ViewHolder) view.getTag(); // 重新获取ViewHolder
                pgname = viewHolder1.pgname;
                pgcount = viewHolder1.pgcount;
            }
            LayPage_C Subpages = (LayPage_C) layPageCList.get(i); // 获取当前项的实例

            String count = String.valueOf(Subpages.getPagecount());
            pgcount.setText(count);//对象为空
            pgname.setText(Subpages.getPagename().toString());

            return view;

        }


        private final class ViewHolder {
            TextView pgname = null;
            TextView pgcount = null;


            public ViewHolder(TextView pgname, TextView pgcount) {
                this.pgname = pgname;
                this.pgcount = pgcount;
            }

        }
    }


    private LayClass_A layClassA;

    public void listClickListener(ArrayList<LayClass_C> layClassCS) {


        layClassA = new LayClass_A(R.layout.unlay_item, this, layClassCS);

        hg_datalist.setAdapter(layClassA);
        hg_datalist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                //Toast.makeText(getContext(), "Click ++ item" + i, Toast.LENGTH_SHORT).show();
                final TextView vod_class1 = (TextView) view.findViewById(R.id.vod_class);
                final TextView vod_score1 = (TextView) view.findViewById(R.id.vod_score);
                final TextView vod_name1 = (TextView) view.findViewById(R.id.vod_name);
                final TextView vod_add_time1 = (TextView) view.findViewById(R.id.vod_add_time);
                final TextView vod_play_url1 = (TextView) view.findViewById(R.id.vod_play_url);
                final TextView vod_value_add1 = (TextView) view.findViewById(R.id.vod_value_add);
                final TextView vod_pic_url1 = (TextView) view.findViewById(R.id.vod_pic_url);

                String vod_class2 = vod_class1.getText().toString();
                String vod_score2 = vod_score1.getText().toString();
                String vod_name2 = vod_name1.getText().toString();
                String vod_add_time2 = vod_add_time1.getText().toString();
                String vod_play_url2 = vod_play_url1.getText().toString();
                String vod_value_add2 = vod_value_add1.getText().toString();
                String vod_pic_url2 = vod_pic_url1.getText().toString();

                Intent intent = new Intent();
                Bundle bundle = new Bundle();
                bundle.putString("vod_class", vod_class2);
                bundle.putString("vod_score", vod_score2);
                bundle.putString("vod_name", vod_name2);
                bundle.putString("vod_add_time", vod_add_time2);
                bundle.putString("vod_play_url", vod_play_url2);
                bundle.putString("vod_value_add", vod_value_add2);
                bundle.putString("vod_pic", vod_pic_url2);
                intent.putExtras(bundle);
                intent.setClass(LayPageActivity.this, PlayerActivity.class);
                startActivity(intent);


            }
        });

    }


}
